//
//  ImageDetailViewController.swift
//  PhotoTestDemo
//
//  Created by 惠 on 2020/9/9.
//  Copyright © 2020 惠. All rights reserved.
//

import UIKit
import Photos
import AVFoundation

class ImageDetailViewController: UIViewController {
    let screenW = UIScreen.main.bounds.width
    let screenH = UIScreen.main.bounds.height
    //选中的图片资源
    var assetsFetchResults:PHFetchResult<PHAsset>!
    //选中的位置
    var index: IndexPath?
    //最多选择图片数量
    var maxSelectPhotoCount: Int = 9
    //最多选择视频数量
    var maxSelectVideoCount: Int = 1
    //选择内容
    var selectedAsset: [PHAsset]?
    //储存选中的下标
    var selectedIndex: [Int]?
    //隐藏上下视图
    var isHiddenView = false
    //用来存放Cell的唯一标示符
    var cellDic: [String: String] = [:]
    //选择代理
    var selectedHandler: (([PHAsset], [Int])-> Swift.Void)?
    var selectedFinishHandler: (([PHAsset])-> Swift.Void)?
    
    var player: AVPlayer?
    
    //类型
    var type: SelectType = .defaults
    var colorType: ColorType!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        //获取当前视图frame
        //        let viewH = view.frame.height
        
    }
    
    //MARK: -设置UI
    func setUI() {
        
        var bottomH: CGFloat = 50
        //获取底部安全距离
        if #available(iOS 11.0, *) {
            if (UIApplication.shared.keyWindow?.safeAreaInsets.bottom ?? 0) > 0 {
                bottomH += 20
            }
        }
        view.addSubview(photoDetailCollectionView)
        photoDetailCollectionView.selectItem(at: index, animated: true, scrollPosition: .centeredHorizontally)
        
        view.addSubview(selectBottomView)
        selectBottomView.frame = CGRect(origin: CGPoint(x: 0, y: screenH-bottomH), size: CGSize(width: screenW, height: bottomH))
        selectBottomView.addSubview(selectLabel)
        selectBottomView.addSubview(selectedCount)
        selectBottomView.addSubview(totalCount)
        selectBottomView.addSubview(nextButton)
        
        selectedCount.text = "\(selectedAsset?.count ?? 0)"
        if selectedAsset?.count ?? 0 > 0 {
            if let myAsset = selectedAsset?[0] {
                if myAsset.mediaType.rawValue == 1 {
                    totalCount.text = "/\(maxSelectPhotoCount))"
                } else if myAsset.mediaType.rawValue == 2 {
                    totalCount.text = "/\(maxSelectVideoCount))"
                }
            }
            selectBottomView.isHidden = false
        }
    }
    
    //MARK: -懒加载UI
    lazy var photoDetailCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        //解决分页偏移问题
        layout.minimumLineSpacing = 0
        layout.itemSize = CGSize(width: screenW, height: screenH)
        let photoDetailCollectionView = UICollectionView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: screenW, height: screenH)), collectionViewLayout: layout)
        photoDetailCollectionView.dataSource = self
        photoDetailCollectionView.delegate = self
        photoDetailCollectionView.backgroundColor = .white
        photoDetailCollectionView.isPagingEnabled = true
        photoDetailCollectionView.showsHorizontalScrollIndicator = false
        return photoDetailCollectionView
    }()
    
    //选中图片
    lazy var selectBottomView: UIView = {
        let selectBottomView = UIView()
        selectBottomView.backgroundColor = .white
        selectBottomView.isHidden = true
        return selectBottomView
    }()
    
    //选择数量
    lazy var selectLabel: UILabel = {
        let selectLabel = UILabel(frame: CGRect(origin: CGPoint(x: 25, y: 10), size: CGSize(width: 55, height: 30)))
        selectLabel.text = "已选择 ("
        selectLabel.textColor = .black
        selectLabel.textAlignment = .left
        selectLabel.font = UIFont.systemFont(ofSize: 14)
        return selectLabel
    }()
    lazy var selectedCount: UILabel = {
        let selectedCount = UILabel(frame: CGRect(origin: CGPoint(x: 78, y: 10), size: CGSize(width: 8, height: 30)))
        selectedCount.text = "0"
        switch colorType {
        case .defaults:
            selectedCount.textColor = UIColor(red: 0.25, green: 0.76, blue: 0.8, alpha: 1)
        case .red:
            selectedCount.textColor = UIColor(red: 0.77, green: 0.16, blue: 0.16, alpha: 1)
        case .none:
            selectedCount.textColor = UIColor(red: 0.25, green: 0.76, blue: 0.8, alpha: 1)
        }
        selectedCount.textAlignment = .left
        selectedCount.font = UIFont.systemFont(ofSize: 14)
        return selectedCount
    }()
    
    lazy var totalCount: UILabel = {
        let totalCount = UILabel(frame: CGRect(origin: CGPoint(x: 88, y: 10), size: CGSize(width: 20, height: 30)))
        totalCount.text = "/9)"
        totalCount.textColor = .black
        totalCount.textAlignment = .left
        totalCount.font = UIFont.systemFont(ofSize: 14)
        return totalCount
    }()
    
    lazy var nextButton: UIButton = {
        let nextButton = UIButton(type: .custom)
        nextButton.frame = CGRect(origin: CGPoint(x: screenW-85, y: 13), size: CGSize(width: 60, height: 24))
        nextButton.setTitle("下一步", for: .normal)
        nextButton.setTitleColor(.white, for: .normal)
        nextButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
        switch colorType {
        case .defaults:
            nextButton.backgroundColor = UIColor(red: 0.25, green: 0.76, blue: 0.8, alpha: 1)
        case .red:
            nextButton.backgroundColor = UIColor(red: 0.77, green: 0.16, blue: 0.16, alpha: 1)
        case .none:
            nextButton.backgroundColor = UIColor(red: 0.25, green: 0.76, blue: 0.8, alpha: 1)
        }
        nextButton.layer.cornerRadius = 12
        nextButton.layer.masksToBounds = true
        nextButton.addTarget(self, action: #selector(nextButtonAction), for: .touchUpInside)
        return nextButton
    }()
    
    //提示框
    let alertVC = UIAlertController(title: "", message: nil, preferredStyle: .alert)
    //定时器
    var timer: Timer?
    
    //MARK: -点击事件
    @objc func backButtonAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func selectedItem(sender: UIButton) {
        let myAsset = self.assetsFetchResults?[sender.tag]
        var sameIndex: Bool = false
        var removeI = 0
        var i = 0
        for index in selectedIndex! {
            if index == sender.tag {
                sameIndex = true
                removeI = i
            }
            i += 1
        }
        
        if sameIndex {
            //删除相同数据
            selectedIndex?.remove(at: removeI)
            sender.isSelected = false
            selectedAsset?.remove(at: removeI)
            self.selectedHandler?(selectedAsset!, selectedIndex!)
        } else {
            if selectedAsset?.count == 0 {
                if type == .photo {
                    if myAsset?.mediaType.rawValue == 1 {
                        selectedIndex?.append(sender.tag)
                        sender.isSelected = true
                        selectedAsset?.append(myAsset!)
                        self.selectedHandler?(selectedAsset!, selectedIndex!)
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            //不同类型
                            self.alertVC.title = "暂不支持视频格式"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else if type == .picture {
                    if myAsset?.mediaType.rawValue == 2 {
                        selectedIndex?.append(sender.tag)
                        sender.isSelected = true
                        selectedAsset?.append(myAsset!)
                        self.selectedHandler?(selectedAsset!, selectedIndex!)
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            //不同类型
                            self.alertVC.title = "暂只支持视频格式"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else {
                    selectedIndex?.append(sender.tag)
                    sender.isSelected = true
                    selectedAsset?.append(myAsset!)
                    self.selectedHandler?(selectedAsset!, selectedIndex!)
                }
            } else {
                let asset = selectedAsset?[0]
                //照片
                if asset?.mediaType.rawValue == 1 {
                    if selectedAsset?.count ?? 0 < maxSelectPhotoCount {
                        if asset?.mediaType == myAsset?.mediaType {
                            selectedIndex?.append(sender.tag)
                            sender.isSelected = true
                            selectedAsset?.append(myAsset!)
                            self.selectedHandler?(selectedAsset!, selectedIndex!)
                        } else {
                            DispatchQueue.main.async {[weak self] in
                                guard let self = self else {return}
                                //不同类型
                                self.alertVC.title = "暂不支持视频格式"
                                self.present(self.alertVC, animated: true, completion: nil)
                                self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                            }
                            
                        }
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            self.alertVC.title = "最多选\(self.maxSelectPhotoCount)张"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                } else if asset?.mediaType.rawValue == 2 {
                    //视频
                    if selectedAsset?.count ?? 0 < maxSelectVideoCount {
                        if asset?.mediaType == myAsset?.mediaType {
                            selectedIndex?.append(sender.tag)
                            sender.isSelected = true
                            selectedAsset?.append(myAsset!)
                            self.selectedHandler?(selectedAsset!, selectedIndex!)
                        } else {
                            DispatchQueue.main.async {[weak self] in
                                guard let self = self else {return}
                                //不同类型
                                self.alertVC.title = "暂只支持视频格式"
                                self.present(self.alertVC, animated: true, completion: nil)
                                self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                            }
                        }
                    } else {
                        DispatchQueue.main.async {[weak self] in
                            guard let self = self else {return}
                            self.alertVC.title = "最多选\(self.maxSelectVideoCount)张"
                            self.present(self.alertVC, animated: true, completion: nil)
                            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.hiddenAlert), userInfo: nil, repeats: false)
                        }
                    }
                }
            }
        }
        selectedCount.text = "\(selectedAsset?.count ?? 0)"
        if selectedAsset?.count ?? 0 > 0 {
            selectBottomView.isHidden = false
            if selectedAsset?[0].mediaType.rawValue == 1 {
                self.totalCount.text = "/\(self.maxSelectPhotoCount))"
            } else {
                self.totalCount.text = "/\(self.maxSelectVideoCount))"
            }
        } else {
            selectBottomView.isHidden = true
        }
    }
    
    //提示框
    @objc func hiddenAlert() {
        alertVC.dismiss(animated: true, completion: nil)
        
        timer?.invalidate()
        timer = nil
    }
    
    //视频播放完毕响应
    @objc func playerDidFinishPlaying() {
        print("播放完毕!")
        
    }
    
    @objc func nextButtonAction() {
        self.selectedFinishHandler?(selectedAsset!)
        self.dismiss(animated: true, completion: nil)
    }
    
}

//MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension ImageDetailViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return assetsFetchResults.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var identifier = cellDic["\(indexPath)"]
        if identifier == nil {
            identifier = "ImageDetailCollectionViewCell\(indexPath)"
            cellDic["\(indexPath)"] = identifier
            photoDetailCollectionView.register(ImageDetailCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: identifier!)
        }
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier!, for: indexPath) as! ImageDetailCollectionViewCell
        cell.colorType = colorType
        cell.tag = indexPath.row
        let myAsset = assetsFetchResults[indexPath.row]
        
        if indexPath.row == index?.row {
            if myAsset.mediaType.rawValue == 2 {
                //获取视频
                let options = PHVideoRequestOptions()
                options.version = .original
                options.deliveryMode = .automatic
                options.isNetworkAccessAllowed = true
                PHCachingImageManager().requestAVAsset(forVideo: myAsset, options:options, resultHandler: { (asset, audioMix, info)in
                    let avAsset = asset as? AVURLAsset
                    let urlString = avAsset?.url
                    
                    if let  urlS = urlString {
                        DispatchQueue.main.async { [weak self] in
                            guard let self = self else { return }
                            //创建媒体资源管理对象
                            let playerItem = AVPlayerItem(url: urlS)
                            //播放完毕发送通知
                            //                        NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
                            //创建ACplayer：负责视频播放
                            self.player = AVPlayer(playerItem: playerItem)
                            self.player?.rate = 1.0//播放速度 播放前设置
                            //创建显示视频的图层
                            let playerLayer = AVPlayerLayer(player: self.player!)
                            playerLayer.videoGravity = .resizeAspect
                            playerLayer.frame = self.view.bounds
                            cell.imageView.layer.addSublayer(playerLayer)
                            //播放
                            self.player?.play()
                        }
                    }
                })
            } else {
                //获取原图
                let options = PHImageRequestOptions()
                options.resizeMode = .fast
                options.isNetworkAccessAllowed = true
                PHImageManager.default().requestImage(for: myAsset,
                                                      targetSize: PHImageManagerMaximumSize , contentMode: .aspectFill,
                                                      options: options, resultHandler: {
                                                        (image, _: [AnyHashable : Any]?) in
                                                        cell.imageView.image = image
                                                      })
            }
        } else {
            //获取原图
            let options = PHImageRequestOptions()
            options.resizeMode = .fast
            options.isNetworkAccessAllowed = true
            PHImageManager.default().requestImage(for: myAsset,
                                                  targetSize: PHImageManagerMaximumSize , contentMode: . aspectFill,
                                                  options: options, resultHandler: {
                                                    (image, _: [AnyHashable : Any]?) in
                                                    cell.imageView.image = image
                                                  })
        }
        var isSelectItem = false
        if let indexs = selectedIndex {
            for index in indexs {
                if index == indexPath.row {
                    isSelectItem = true
                }
            }
        }
        cell.checkItemButton.isSelected = isSelectItem
        cell.navView.isHidden = isHiddenView
        cell.backButton.addTarget(self, action: #selector(backButtonAction), for: .touchUpInside)
        cell.checkItemButton.tag = indexPath.item
        cell.checkItemButton.addTarget(self, action: #selector(selectedItem(sender:)), for: .touchUpInside)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! ImageDetailCollectionViewCell
        if !isHiddenView {
            cell.navView.isHidden = true
            selectBottomView.isHidden = true
        } else {
            cell.navView.isHidden = false
            if selectedAsset?.count ?? 0 > 0 {
                selectBottomView.isHidden = false
            }
        }
        isHiddenView = !isHiddenView
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.player?.pause()
        let currentIndex = photoDetailCollectionView.visibleCells[0].tag
        let views = photoDetailCollectionView.subviews
        for (_, view) in views.enumerated() {
            if let cell = view as? ImageDetailCollectionViewCell {
                if currentIndex != cell.tag {
                    cell.imageView.layer.removeAllAnimations()
                }
            }
        }
        
        let myAsset = assetsFetchResults[currentIndex]
        let currentCell = photoDetailCollectionView.visibleCells[0] as? ImageDetailCollectionViewCell
        if myAsset.mediaType.rawValue == 2 {
            //获取视频
            let options = PHVideoRequestOptions()
            options.version = .original
            options.deliveryMode = .automatic
            options.isNetworkAccessAllowed = true
            PHCachingImageManager().requestAVAsset(forVideo: myAsset, options:options, resultHandler: { (asset, audioMix, info)in
                let avAsset = asset as? AVURLAsset
                let urlString = avAsset?.url
                
                if let  urlS = urlString {
                    DispatchQueue.main.async { [weak self] in
                        guard let self = self else { return }
                        //创建媒体资源管理对象
                        let playerItem = AVPlayerItem(url: urlS)
                        //播放完毕发送通知
                        //                        NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem)
                        //创建ACplayer：负责视频播放
                        self.player = AVPlayer(playerItem: playerItem)
                        self.player?.rate = 1.0//播放速度 播放前设置
                        //创建显示视频的图层
                        let playerLayer = AVPlayerLayer(player: self.player!)
                        playerLayer.videoGravity = .resizeAspect
                        playerLayer.frame = self.view.bounds
                        currentCell?.imageView.layer.addSublayer(playerLayer)
                        //播放
                        self.player?.play()
                    }
                }
            })
        }
    }
}
